import datastructure.linklist.ListNode;

/**
 * @Author ZhangCuirong
 * @Date 2025/8/28 15:55
 * @description:
 */
public class Solution61 {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null){
            return null;
        }
        int length = 0;
        ListNode p = head;
        while (p != null) {
            p = p.next;
            length++;
        }
        k %= length;
        ListNode slow = head;
        ListNode fast = head;
        while (k-- != 0) {
            fast = fast.next;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        fast.next = head;
        ListNode res = slow.next;
        slow.next = null;
        return res;
    }

    public static void main(String[] args) {
        Solution61 solution = new Solution61();
        ListNode head = ListNode.arrayToList(new int[]{1, 2, 3, 4, 5});
        ListNode newHead = solution.rotateRight(head, 2);
        ListNode.printListWithCycleCheck(newHead);
        head = ListNode.arrayToList(new int[]{0, 1, 2});
        newHead = solution.rotateRight(head, 4);
        ListNode.printListWithCycleCheck(newHead);

    }
}
